package org.wlgzs.shop.service.impl;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
import javax.servlet.http.HttpSession;

/**
 * @author 王言
 *
 * from="自定义昵称"，可以自己定义想要使用的发送昵称
 * toMail=是接收方的email
 * mailTitle=是邮件的标题
 *  mailContent=是邮件的内容，支持html
 */

public class SendEmail {
    public static void sendEmail(String from,String toMail,String
            mailTitle,String mailContent ) throws UnsupportedEncodingException, MessagingException {
        String fromEmail="614200978@qq.com";//发件人的邮箱
        String password="paguelxxkucwbfjc";//邮箱授权码
        Properties properties=new Properties();
        properties.put("mail.smtp.host", "smtp.qq.com");//存储发送邮件服务器的信息,qq为例，如果是163则是smtp.163.com
        properties.put("mail.transport.protocol","smtp");//使用smtp简单邮件传输协议
        properties.put("mail.smtp.auth", "true");//是否需要身份验证
        properties.put("mail.smtp.ssl.enable", "true");//QQ邮箱的SSL加密
        Session session=Session.getInstance(properties);
        session.setDebug(true);////开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        //由邮件会话创建一个扩展信息对象
        MimeMessage msg = new MimeMessage(session);
        //自定义昵称
        String nick = MimeUtility.encodeText(from);//防止乱码
        msg.setFrom(new InternetAddress(nick+"<"+fromEmail+">"));
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toMail));//设置收件人，并设置其接受类型为to
        msg.setSubject(mailTitle);//设置标题
        //设置为html格式，可以发送多种样式
        msg.setContent(mailContent,"text/html;charset=UTF-8");
        //msg.setSentDate(new Date());  //设置发信时间
        msg.saveChanges(); //存储邮件信息
        //使用smtp协议获取session环境的Transprot对象来发送邮件 javamial使用
        //Transport对象来管理发送邮件服务
        Transport tran = session.getTransport("smtp");
        tran.connect(properties.getProperty("mail.smtp.host"),fromEmail,
                password);//链接邮箱服务器，发送邮件的邮箱，以及授权码
        //发送邮件，getAllRecipients()是所有已设好的收件人地址
        tran.sendMessage(msg, msg.getAllRecipients());
        tran.close();
    }


    public static String verifyCode() {
        Random random = new Random();
        String str = "";
        for (int i = 0; i < 6; i++){
            int key = random.nextInt(3);
            switch (key){
                case 0:
                    int code1 = random.nextInt(10);
                    str += code1;
                    break;
                case 1:
                    char code2 = (char)(random.nextInt(26)+65);
                    str += code2;
                    break;
                case 2:
                    char code3 = (char)(random.nextInt(26)+97);
                    str += code3;
                    break;
            }
        }
        return str;
    }

    /**
     * 发送验证码
     * userEmail=收信人的邮箱
     * 五分钟后验证码失效
     */
    public static void sendCode(String userEmail, final HttpSession session) throws UnsupportedEncodingException, MessagingException {
        String code = verifyCode();
        final Timer timer=new Timer();
        sendEmail("小金库",userEmail,"验证码","验证码为:"+code);
        session.setAttribute("checkNumber",code);

//        timer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                session.removeAttribute("checkNumber");
//                timer.cancel();
//            }
//        },5*60*1000);
    }

    @Test
    public void test() throws UnsupportedEncodingException, MessagingException {
        sendEmail("小金库","614200978@qq.com","测试","<div>测试成功！！</div>");
    }
}
